<template>
  <div class="index">
    <el-card class="box-card">
      <div class="main-container">
        <div class="contentMain">
          <div>
            <el-form ref="form" :model="personalForm" label-width="80px">
              <el-form-item>
                <el-upload
                  class="avatar-uploader"
                  action="http://localhost:8001/api/upload/oss"
                  :on-success="handleAvatarSuccess"
                  :headers="headers"
                  :show-file-list="false"
                  :before-upload="oss_upload"
                >
                  <el-image
                    class="avatar"
                    v-if="personalForm.avatar != null"
                    :src="personalForm.avatar"
                  ></el-image>
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>
              <el-form-item label="登入名">
                <el-input
                  :readonly="true"
                  class="input-width-250"
                  size="small"
                  v-model="personalForm.username"
                ></el-input>
              </el-form-item>
              <el-form-item label="昵称">
                <el-input
                  class="input-width-250"
                  size="small"
                  v-model="personalForm.nickName"
                ></el-input>
              </el-form-item>
              <el-form-item label="手机">
                <el-input
                  class="input-width-250"
                  :disabled="true"
                  size="small"
                  v-model="personalForm.phone"
                >
                  <el-button
                    @click="bindingModification(personalForm.id, 'phone')"
                    slot="append"
                    class="update_button"
                  >
                    <span v-if="personalForm.phone">修改</span>
                    <span v-else>绑定</span>
                  </el-button>
                </el-input>
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input
                  class="input-width-250"
                  :disabled="true"
                  size="small"
                  v-model="personalForm.email"
                >
                  <el-button
                    @click="bindingModification(personalForm.id, 'email')"
                    slot="append"
                    class="update_button"
                  >
                    <span v-if="personalForm.email">修改</span>
                    <span v-else>绑定</span>
                  </el-button>
                </el-input>
              </el-form-item>
              <el-form-item label="人脸录入">
                <el-button
                  type="text"
                  class="text-red"
                  :disabled="this.faceFlag"
                  v-if="this.isFace === false"
                  @click="inputFace()"
                >
                  <i class="el-icon-error" /> 未录入
                </el-button>
                <el-button
                  type="text"
                  class="text-blue"
                  v-if="this.isFace === true"
                >
                  <i class="el-icon-success" /> 已录入
                </el-button>
              </el-form-item>
              <el-form-item label="隐藏自己">
                <el-select
                  class="button-width-80"
                  size="small"
                  v-model="personalForm.allowSearching"
                  placeholder="是否允许被搜索"
                >
                  <el-option label="是" :value="0"></el-option>
                  <el-option label="否" :value="1"></el-option>
                </el-select>
                <div
                  class="error-message"
                  v-show="personalForm.allowSearching === 0"
                >
                  其他人将无法搜索到你
                </div>
              </el-form-item>
              <el-form-item label="性别">
                <el-select
                  class="button-width-150"
                  size="small"
                  v-model="personalForm.gender"
                  placeholder="选择性别"
                >
                  <el-option label="女" :value="0"></el-option>
                  <el-option label="男" :value="1"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="生日">
                <div class="block">
                  <el-date-picker
                    size="small"
                    v-model="personalForm.dateBirth"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="选择日期"
                  ></el-date-picker>
                </div>
              </el-form-item>
              <el-form-item label="住址">
                <el-input
                  class="input-width-300"
                  type="textarea"
                  v-model="personalForm.address"
                ></el-input>
              </el-form-item>
              <el-form-item label="简介">
                <el-input
                  class="input-width-300"
                  maxlength="20"
                  show-word-limit
                  type="textarea"
                  v-model="personalForm.intro"
                ></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="info" @click="cancel">取消</el-button>
                <el-button type="primary" @click="onSubmit">提交</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div class="sidebar-container">
          <el-button
            type="info"
            @click="visualization"
            v-if="!visualizationShow"
          >
            <span>展开数据</span>
            <i class="el-icon-arrow-down"></i>
          </el-button>
          <el-button
            type="primary"
            @click="visualization"
            v-if="visualizationShow"
          >
            <span>关闭数据</span>
            <i class="el-icon-arrow-up"></i>
          </el-button>
        </div>
        <!--                图形化-->
        <transition name="el-zoom-in-top">
          <div class="visualization" v-show="visualizationShow">
            <div>
              <el-row :gutter="31">
                <el-col :span="8">
                  <el-card>
                    <div class="card-icon-container">
                      <FriendCount class="card-icon-container" />
                    </div>
                    <div class="card-desc">
                      <div class="card-title">好友数</div>
                      <div class="card-count">{{ this.friendCount }}</div>
                    </div>
                  </el-card>
                </el-col>
                <el-col :span="8">
                  <el-card>
                    <div class="card-icon-container">
                      <GroupChatCount class="card-icon-container" />
                    </div>
                    <div class="card-desc">
                      <div class="card-title">群聊数</div>
                      <div class="card-count">{{ this.groupChatCount }}</div>
                    </div>
                  </el-card>
                </el-col>
                <el-col :span="8">
                  <el-card>
                    <div
                      class="card-icon-container cursor-pointer"
                      @click="eyesStatus = !eyesStatus"
                    >
                      <Purse class="card-icon-container" v-show="eyesStatus" />
                      <CloseMoney
                        class="card-icon-container"
                        v-show="!eyesStatus"
                      ></CloseMoney>
                    </div>
                    <div class="card-desc">
                      <div class="card-title flex-center">
                        <span>钱包（元）</span>
                        <div class="recharge" @click="rechargeView = true">
                          充值
                        </div>
                      </div>
                      <div v-show="!eyesStatus" class="card-count">
                        <span class="el-icon-more"></span>
                      </div>
                      <div class="card-count" v-show="eyesStatus">
                        {{ amount }}
                      </div>
                    </div>
                  </el-card>
                </el-col>
              </el-row>
            </div>
            <div>
              <el-card class="margin-top-1rem">
                <span class="font-bold">近期活跃视图</span>
                <ChatHistoryAnalysis
                  v-if="chatHistoryData"
                  :chatHistoryData="chatHistoryData"
                />
              </el-card>
            </div>
            <div class="height-320">
              <el-card class="margin-top-1rem">
                <span class="font-bold">异地通知</span>
                <div
                  class="height-240"
                  v-if="
                    loginRecordsDTOList != null &&
                    loginRecordsDTOList.length > 0
                  "
                >
                  <el-scrollbar
                    class="full-size"
                    wrap-style="overflow-x:hidden;"
                  >
                    <div class="flex-center-column">
                      <div v-for="loginRecord in loginRecordsDTOList" :key="loginRecord.id">
                        <el-card class="margin-10">
                          <div class="main notification-card">
                            <div class="title">
                              <span>
                                <i class="el-icon-warning text-red"></i>
                                {{ loginRecord.title }}
                              </span>
                            </div>
                            <div class="description">
                              {{ loginRecord.description }}
                            </div>
                            <div class="detail">
                              <div>
                                <span class="title">登入时间:</span>
                                <span>{{ loginRecord.createTime }}</span>
                              </div>
                              <div>
                                <span class="title">登入方式:</span>
                                <span>{{ loginRecord.loginMethod }}</span>
                              </div>
                              <div>
                                <span class="title">登入地点:</span>
                                <span>{{ loginRecord.ipSource }}</span>
                              </div>
                            </div>
                            <div class="suggestion">
                              <span>{{ loginRecord.suggestion }}</span>
                            </div>
                            <div class="operate" @click="updatePassword">
                              <span>修改密码</span>
                              <span
                                class="float-right el-icon-arrow-right"
                              ></span>
                            </div>
                          </div>
                        </el-card>
                      </div>
                    </div>
                  </el-scrollbar>
                </div>
                <div v-else class="height-240">
                  <div>
                    <el-empty description="暂无数据"></el-empty>
                  </div>
                </div>
              </el-card>
            </div>
          </div>
        </transition>
      </div>
    </el-card>
    <UpdateEmailOrPhone ref="updateEmailOrPhone" />

    <el-dialog
      title="修改密码"
      :visible.sync="updatePasswordView"
      :before-close="updatePasswordClose"
      width="30%"
      center
    >
      <el-form
        ref="updatePasswordForm"
        :rules="rules"
        :model="updatePasswordForm"
        label-width="80px"
      >
        <el-form-item label="原密码" prop="oldPassword">
          <el-input
            size="small"
            v-model="updatePasswordForm.oldPassword"
            placeholder="输入原密码"
            prefix-icon="el-icon-key"
            class="input-width-250"
          ></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            type="password"
            show-password
            prefix-icon="el-icon-lock"
            placeholder="输入新密码"
            v-model="updatePasswordForm.newPassword"
            size="small"
            class="input-width-250"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            type="password"
            show-password
            prefix-icon="el-icon-lock"
            placeholder="再次输入新密码"
            v-model="updatePasswordForm.confirmPassword"
            size="small"
            class="input-width-250"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="updatePasswordClose">取 消</el-button>
        <el-button type="primary" @click="update('updatePasswordForm')"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!--        充值-->
    <el-dialog
      class="recharge-dialog"
      title="充值"
      :visible.sync="rechargeView"
      width="30%"
      :before-close="rechargeClose"
      center
    >
      <el-form
        ref="aliPay"
        :rules="aliPayRules"
        :model="aliPay"
        label-width="80px"
      >
        <el-form-item label="充值金额" prop="totalAmount">
          <el-input-number
            v-model="aliPay.totalAmount"
            size="small"
            :precision="2"
            :step="1"
            :max="1000"
            :min="0"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="支付方式">
          <el-radio-group v-model="payType">
            <el-radio :label="0" v-model="payType">支付宝</el-radio>
            <el-radio :label="1" v-model="payType">微信</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="rechargeClose">关 闭</el-button>
        <el-button type="primary" @click="recharge('aliPay')">充 值</el-button>
      </span>
    </el-dialog>
    <!--        人脸录入提示-->
    <el-dialog
      title="人脸录入注意事项"
      :visible.sync="faceView"
      :before-close="faceClose"
      width="60%"
      center
    >
      <div class="height-350">
        <el-scrollbar
          style="height: 100%; width: 100%"
          wrap-style="overflow-x:hidden;"
        >
          <FaceIllustrate />
        </el-scrollbar>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="faceClose()">取 消</el-button>
        <el-button type="info" v-show="this.faceCountdown > 0" disabled
          >（{{ this.faceCountdown }}）进入人脸录入</el-button
        >
        <el-button
          type="primary"
          @click="faceEntry()"
          v-show="this.faceCountdown <= 0"
          >进入人脸录入</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import GroupChatCount from "@/assets/icon/group-chat-count.svg";
import ActivityValue from "@/assets/icon/activity-value.svg";
import FriendCount from "@/assets/icon/friend-count.svg";
import Purse from "@/assets/icon/purse.svg";
import Money from "@/assets/icon/money.svg";
import CloseMoney from "@/assets/icon/close-money.svg";
import OpenEyes from "@/assets/icon/open-eyes.svg";
import ChatHistoryAnalysis from "../../components/Setting/ChatHistoryAnalysis";
import service from "../../utils/request";
import UpdateEmailOrPhone from "../../components/Setting/UpdateEmailOrPhone";
import store from "../../store";
import FaceIllustrate from "../../components/FaceRecognition/FaceIllustrate";
export default {
  components: {
    FaceIllustrate,
    UpdateEmailOrPhone,
    ChatHistoryAnalysis,
    FriendCount,
    GroupChatCount,
    ActivityValue,
    CloseMoney,
    OpenEyes,
    Money,
    Purse,
  },
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.updatePasswordForm.confirmPassword !== "") {
          this.$refs.updatePasswordForm.validateField("confirmPassword");
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.updatePasswordForm.newPassword) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    var rechargeValidate = (rule, value, callback) => {
      // 最多只有两位小数的正则表达式
      var reg = /(^[1-9](\d+)?(\.\d{1,2})?$)|(^0$)|(^\d\.\d{1,2}$)/;

      // 输入金额判断
      // 未输入充值金额
      if (!value) {
        callback(new Error("充值金额格式不正确"));
      }
      // 判断充值金额是否正确
      else if (!reg.test(value)) {
        callback(new Error("充值金额格式不正确"));
      }
      // 判断充值金额是否为0、0.0、0.00
      else if (value == 0) {
        callback(new Error("充值金额必须大于0"));
      }
      // 充值金额输入正确
      else {
        callback();
      }
    };
    return {
      headers: { Authorization: "Bearer " + store.getters.token },
      eyesStatus: false,
      faceView: false,
      objectData: {
        OSSAccessKeyId: "",
        policy: "",
        Signature: "",
        key: "",
        host: "",
        dir: "",
      },
      updatePasswordForm: {
        oldPassword: null,
        newPassword: null,
        confirmPassword: null,
      },
      aliPay: {
        traceNo: 11112222552,
        totalAmount: 0,
        subject: "recharge",
        alipayTraceNo: "",
      },
      faceFlag: false,
      faceCountdown: 6,
      faceInterval: null,
      payType: 0,
      rechargeView: false,
      visualizationShow: false,
      friendCount: 0,
      groupChatCount: 0,
      chatHistoryData: null,
      amount: 0,
      loginRecordsDTOList: null,
      fits: ["fill", "contain", "cover", "none", "scale-down"],
      imageUrl: null,
      dialogImageUrl: "",
      updatePasswordView: false,
      isFace: null,
      personalForm: {
        username: "",
        avatar: "",
        nickName: "",
        gender: 1,
        allowSearching: null,
        address: "",
        dateBirth: "",
        phone: "",
        email: "",
        intro: null,
      },
      aliPayRules: {
        totalAmount: [{ validator: rechargeValidate, trigger: "blur" }],
      },
      rules: {
        oldPassword: [
          {
            type: "string",
            required: true,
            message: "旧密码不能为空",
            trigger: "blur",
          },
        ],
        newPassword: [{ validator: validatePass, trigger: "blur" }],
        confirmPassword: [{ validator: validatePass2, trigger: "blur" }],
      },
    };
  },
  methods: {
    onSubmit() {
      this.personalForm.dateBirth = new Date(this.personalForm.dateBirth);
      service({
        method: "post",
        url: "users/save/userInfo",
        data: this.personalForm,
      }).then((res) => {
        var userInfo = this.$store.getters.userLogin;
        if (!userInfo) {
          console.warn('用户信息未加载，无法更新个人信息');
          return;
        }
        if (res.code) {
          userInfo.avatar = res.data.avatar;
          userInfo.nickName = res.data.nickName;
          userInfo.gender = res.data.gender;
          userInfo.dateBirth = res.data.dateBirth;
          userInfo.address = res.data.address;
          userInfo.username = res.data.username;
          this.$store.dispatch("user/updateUserInfo", userInfo);
          this.$notify({
            title: "个人信息",
            type: "success",
            message: "修改成功",
          });
        }
      });
    },
    recharge(aliPay) {
      this.$refs[aliPay].validate((valid) => {
        if (valid) {
          service({
            method: "get",
            url: "/users/create/rechargenumber",
          }).then((res) => {
            this.aliPay.traceNo = res.message;
            if (this.payType == 0) {
              window.open(
                `http://121.40.137.206:8088/alipay/pay?subject=${this.aliPay.subject}&traceNo=${this.aliPay.traceNo}&totalAmount=${this.aliPay.totalAmount}`
              );
              this.rechargeView = false;
            }
            this.aliPay = {
              traceNo: 0,
              totalAmount: 0,
              subject: "recharge",
              alipayTraceNo: "",
            };
            this.payType = 0;
          });

          return false;
        } else {
        }
      });
    },
    inputFace() {
      this.faceFlag = true;
      service({
        method: "get",
        url: "users/allow/faces",
      })
        .then((res) => {
          if (!res.flag) {
            this.$notify({
              title: "人脸录入",
              message: res.message || "不符合人脸录入条件",
            });
          } else {
            this.faceView = true;
            this.startCountdown();
          }
          this.faceFlag = false;
        })
        .catch(() => {
          this.faceFlag = false;
        });
    },
    faceEntry() {
      this.faceView = false;
      this.$router.push("/face-entry");
    },
    startCountdown() {
      var _this = this;
      this.faceCountdown = 6;
      this.faceInterval = setInterval(function () {
        // 更新倒计时
        // 如果倒计时结束，清除定时器并显示结束信息
        if (_this.faceCountdown <= 0) {
          clearInterval(_this.faceInterval);
        } else {
          // 否则，倒计时减一
          _this.faceCountdown--;
        }
      }, 1000);
    },
    updateAmountCount(event) {
      this.amount = event.detail.data.data;
    },
    oss_upload(file) {
      const isJPG = file.type === "image/png" || file.type === "image/jpeg";
      if (!isJPG) {
        this.$notify({
          title: "上传头像图片",
          type: "error",
          message: "上传头像图片只能是 JPG 格式!",
        });
      }
      return isJPG;
    },
    getData() {
      service({
        method: "get",
        url: "/users",
      }).then((res) => {
        this.friendCount = res.data.friendCount;
        this.groupChatCount = res.data.groupChatCount;
        this.chatHistoryData = res.data.chatHistoryDTOList;
        this.amount = res.data.amount;
        this.loginRecordsDTOList = res.data.loginRecordsDTOList;
      });
    },
    visualization() {
      this.visualizationShow = !this.visualizationShow;
    },
    handleAvatarSuccess(res, file) {
      this.personalForm.avatar = res.data;
    },
    cancel() {
      this.getUserInfo();
    },
    getUserInfo() {
      service.get("users/userInfo/personal").then((res) => {
        this.personalForm = res.data;
      });
    },
    checkFace() {
      service.get("/users/check/face/").then((res) => {
        if (res.flag) {
          this.isFace = res.data;
        }
      });
    },
    bindingModification(id, type) {
      this.$refs.updateEmailOrPhone.selectUpdateView(id, type);
    },
    updatePassword() {
      this.updatePasswordView = true;
    },
    update(updatePasswordForm) {
      this.$refs[updatePasswordForm].validate((valid) => {
        if (valid) {
          service({
            method: "post",
            url: "users/update/password",
            data: this.updatePasswordForm,
          }).then((res) => {
            if (res.code === 200) {
              this.updatePasswordView = false;
              this.$store.dispatch("user/resetToken");
              this.$router.replace("/login");
              this.$notify({
                title: "密码修改",
                type: "success",
                message: "修改成功，请重新登入",
              });
            }
          });
        } else {
        }
      });
    },
    updatePasswordClose() {
      this.$confirm("确认关闭？")
        .then((_) => {
          this.$refs.updatePasswordForm.resetFields();
          this.updatePasswordView = false;
        })
        .catch((_) => {});
    },
    rechargeClose() {
      this.$confirm("确认关闭充值窗口？")
        .then((_) => {
          this.rechargeView = false;
          this.aliPay = {
            traceNo: 11112222552,
            totalAmount: 0,
            subject: "recharge",
            alipayTraceNo: "",
          };
          this.payType = 0;
        })
        .catch((_) => {});
    },
    faceClose() {
      this.faceView = false;
      if (this.faceInterval) {
        clearInterval(this.faceInterval);
      }
    },
  },
  mounted() {
    this.getData();
    this.getUserInfo();
    this.checkFace();
    window.addEventListener("updateAmountCount", this.updateAmountCount);
  },
  beforeDestroy() {
    if (this.faceInterval) {
      clearInterval(this.faceInterval);
    }
  },
};
</script>
<style>
.index {
  margin: 20px auto;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}

.box-card {
  margin: 0 auto;
  width: 97%;
}

.contentMain {
  /* 主要内容区域样式 */
}

.update_button :hover {
  color: #adadad;
}

.visualization {
  margin-left: 3rem;
  display: flex;
  flex-direction: column;
}

.card-icon-container {
  display: inline-block;
  width: 60px;
  height: 60px;
}

.card-desc {
  font-weight: bold;
  float: right;
}

.card-title {
  margin-top: 0.3rem;
  line-height: 18px;
  color: rgba(0, 0, 0, 0.45);
  font-size: 1rem;
}

.card-count {
  margin-top: 0.75rem;
  color: #666;
  font-size: 1.25rem;
}

.el-carousel__item h3 {
  color: #475669;
  font-size: 14px;
  opacity: 0.75;
  line-height: 200px;
  margin: 0;
}

.main .title {
  font-weight: bold;
}

.main .description {
  margin-top: 10px;
  font-size: 14px;
}

.main .suggestion {
  margin-bottom: 10px;
  font-size: 14px;
}

.main .detail {
  display: flex;
  flex-direction: column;
  margin: 10px 0 10px 0;
}

.main .detail div {
  margin-top: 5px;
}

.main .detail .title {
  font-size: 14px;
  color: #999999;
  margin-right: 8px;
}

.main .operate {
  font-weight: 600;
  color: #9993f9;
  font-size: 14px;
  cursor: pointer;
  padding-top: 8px;
  border-top: 1px solid #999999;
}

.main .operate:hover {
  color: #8776f9;
}

.recharge {
  color: #409eff;
  cursor: pointer;
}

.recharge:hover {
  color: #337bca;
}

.echarge-dialog .el-dialog__wrapper {
  top: 80px !important;
}

/* 提取的内联样式 */
.main-container {
  display: flex;
  flex-direction: row;
}

.input-width-250 {
  width: 250px;
}

.input-width-300 {
  width: 300px;
}

.text-red {
  color: red;
}

.text-blue {
  color: #4c97ff;
}

.button-width-80 {
  width: 80px;
}

.button-width-150 {
  width: 150px;
}

.error-message {
  position: absolute;
  top: 28px;
  color: red;
  font-size: 10px;
}

.sidebar-container {
  display: flex;
  flex-direction: column;
}

.cursor-pointer {
  cursor: pointer;
}

.flex-center {
  display: flex;
  align-items: center;
}

.margin-top-1rem {
  margin-top: 1rem;
}

.font-bold {
  font-weight: bold;
}

.height-320 {
  height: 320px;
}

.height-240 {
  height: 240px;
}

.height-350 {
  height: 350px;
}

.full-size {
  height: 100%;
  width: 100%;
}

.flex-center-column {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.margin-10 {
  margin: 10px;
}

.notification-card {
  height: 225px;
  width: 350px;
  margin: 10px;
}

.float-right {
  float: right;
  padding-top: 3px;
}
</style>
